package com.honghe.web.controller.system;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.honghe.common.annotation.Log;
import com.honghe.common.core.controller.BaseController;
import com.honghe.common.core.domain.AjaxResult;
import com.honghe.common.enums.BusinessType;
import com.honghe.common.utils.SecurityUtils;
import com.honghe.system.domain.SysAttendance;
import com.honghe.system.domain.SysAttendanceSettings;
import com.honghe.system.domain.vo.AttendanceStatsVO;
import com.honghe.system.service.ISysAttendanceService;
import com.honghe.system.service.ISysAttendanceSettingsService;
import com.honghe.common.utils.poi.ExcelUtil;
import com.honghe.common.core.page.TableDataInfo;
import com.honghe.system.domain.SysAttendanceReapply;
import com.honghe.system.domain.SysAttendanceLeave;
import com.honghe.system.service.ISysAttendanceReapplyService;
import com.honghe.system.service.ISysAttendanceLeaveService;

/**
 * 员工打卡记录Controller
 * 
 * @author honghe
 */
@RestController
@RequestMapping("/system/attendance")
public class SysAttendanceController extends BaseController
{
    @Autowired
    private ISysAttendanceService sysAttendanceService;
    
    @Autowired
    private ISysAttendanceSettingsService sysAttendanceSettingsService;
    
    @Autowired
    private ISysAttendanceReapplyService attendanceReapplyService;
    
    @Autowired
    private ISysAttendanceLeaveService attendanceLeaveService;

    /**
     * 查询员工打卡记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysAttendance sysAttendance)
    {
        startPage();
        List<SysAttendance> list = sysAttendanceService.selectSysAttendanceList(sysAttendance);
        return getDataTable(list);
    }
    
    /**
     * 获取当天打卡状态
     */
    @GetMapping("/today")
    public AjaxResult getTodayStatus(@RequestParam(required = false) Long userId) {
        // 如果没有提供用户ID，则使用当前登录用户的ID
        if (userId == null) {
            userId = SecurityUtils.getUserId();
        }
        // 如果不是管理员，只能查询自己的打卡记录
        else if (!SecurityUtils.isAdmin(SecurityUtils.getUserId()) && !userId.equals(SecurityUtils.getUserId())) {
            userId = SecurityUtils.getUserId();
        }
        return success(sysAttendanceService.selectTodayAttendance(userId));
    }
    
    /**
     * 获取打卡统计数据
     */
    @GetMapping("/stats")
    public AjaxResult getAttendanceStats(SysAttendance sysAttendance)
    {
        // 如果不是管理员，只能查询自己的打卡统计
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId()))
        {
            sysAttendance.setUserId(SecurityUtils.getUserId());
        }
        AttendanceStatsVO stats = sysAttendanceService.selectAttendanceStats(sysAttendance);
        return success(stats);
    }
    
    /**
     * 获取打卡图表数据
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:stats')")
    @GetMapping("/chart")
    public AjaxResult getAttendanceChartData(@RequestParam Map<String, Object> params)
    {
        return success(sysAttendanceService.selectAttendanceChartData(params));
    }
    
    /**
     * 获取考勤设置
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:edit')")
    @GetMapping("/settings")
    public AjaxResult getAttendanceSettings()
    {
        return success(sysAttendanceSettingsService.selectSysAttendanceSettings());
    }
    
    /**
     * 更新考勤设置
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:edit')")
    @Log(title = "考勤设置", businessType = BusinessType.UPDATE)
    @PutMapping("/settings")
    public AjaxResult updateAttendanceSettings(@RequestBody SysAttendanceSettings sysAttendanceSettings)
    {
        return toAjax(sysAttendanceSettingsService.updateSysAttendanceSettings(sysAttendanceSettings));
    }

    /**
     * 导出员工打卡记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:export')")
    @Log(title = "员工打卡记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysAttendance sysAttendance)
    {
        List<SysAttendance> list = sysAttendanceService.selectSysAttendanceList(sysAttendance);
        ExcelUtil<SysAttendance> util = new ExcelUtil<SysAttendance>(SysAttendance.class);
        util.exportExcel(response, list, "员工打卡记录数据");
    }

    /**
     * 获取员工打卡记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:query')")
    @GetMapping(value = "/{attendanceId}")
    public AjaxResult getInfo(@PathVariable("attendanceId") Long attendanceId)
    {
        return success(sysAttendanceService.selectSysAttendanceByAttendanceId(attendanceId));
    }

    /**
     * 新增员工打卡记录
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:add')")
    @Log(title = "员工打卡记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysAttendance sysAttendance)
    {
        sysAttendance.setCreateBy(getUsername());
        return toAjax(sysAttendanceService.insertSysAttendance(sysAttendance));
    }
    
    /**
     * 用户签到
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:clock')")
    @Log(title = "用户签到", businessType = BusinessType.INSERT)
    @PostMapping("/clockIn")
    public AjaxResult clockIn(@RequestBody SysAttendance sysAttendance)
    {
        return toAjax(sysAttendanceService.clockIn(sysAttendance.getClockInLocation(), sysAttendance.getRemark()));
    }
    
    /**
     * 用户签退
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:clock')")
    @Log(title = "用户签退", businessType = BusinessType.UPDATE)
    @PostMapping("/clockOut")
    public AjaxResult clockOut(@RequestBody SysAttendance sysAttendance)
    {
        return toAjax(sysAttendanceService.clockOut(sysAttendance.getAttendanceId(), sysAttendance.getClockOutLocation(), sysAttendance.getRemark()));
    }

    /**
     * 修改员工打卡记录
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:edit')")
    @Log(title = "员工打卡记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysAttendance sysAttendance)
    {
        sysAttendance.setUpdateBy(getUsername());
        return toAjax(sysAttendanceService.updateSysAttendance(sysAttendance));
    }

    /**
     * 删除员工打卡记录
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:remove')")
    @Log(title = "员工打卡记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{attendanceIds}")
    public AjaxResult remove(@PathVariable Long[] attendanceIds)
    {
        return toAjax(sysAttendanceService.deleteSysAttendanceByAttendanceIds(attendanceIds));
    }

    /**
     * 提交补卡申请
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:clock')")
    @Log(title = "员工打卡记录", businessType = BusinessType.INSERT)
    @PostMapping("/reapply")
    public AjaxResult reapply(@RequestBody SysAttendanceReapply reapply)
    {
        return toAjax(attendanceReapplyService.applyReapply(reapply));
    }
    
    /**
     * 提交请假申请
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:clock')")
    @Log(title = "员工打卡记录", businessType = BusinessType.INSERT)
    @PostMapping("/leave")
    public AjaxResult leave(@RequestBody SysAttendanceLeave leave)
    {
        return toAjax(attendanceLeaveService.applyLeave(leave));
    }
    
    /**
     * 查询补卡申请列表
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:list')")
    @GetMapping("/reapply/list")
    public TableDataInfo reapplyList(SysAttendanceReapply reapply)
    {
        startPage();
        List<SysAttendanceReapply> list = attendanceReapplyService.selectSysAttendanceReapplyList(reapply);
        return getDataTable(list);
    }
    
    /**
     * 查询请假申请列表
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:list')")
    @GetMapping("/leave/list")
    public TableDataInfo leaveList(SysAttendanceLeave leave)
    {
        startPage();
        List<SysAttendanceLeave> list = attendanceLeaveService.selectSysAttendanceLeaveList(leave);
        return getDataTable(list);
    }
    
    /**
     * 删除补卡申请
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:remove')")
    @Log(title = "补卡申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/reapply/{reapplyId}")
    public AjaxResult removeReapply(@PathVariable Long reapplyId)
    {
        return toAjax(attendanceReapplyService.deleteSysAttendanceReapplyByReapplyId(reapplyId));
    }
    
    /**
     * 删除请假申请
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:remove')")
    @Log(title = "请假申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/leave/{leaveId}")
    public AjaxResult removeLeave(@PathVariable Long leaveId)
    {
        return toAjax(attendanceLeaveService.deleteSysAttendanceLeaveByLeaveId(leaveId));
    }
    
    /**
     * 审批补卡申请
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:edit')")
    @Log(title = "补卡申请审批", businessType = BusinessType.UPDATE)
    @PutMapping("/reapply/approve/{reapplyId}")
    public AjaxResult approveReapply(@PathVariable Long reapplyId, @RequestBody Map<String, Object> params)
    {
        String status = (String) params.get("status");
        String remark = (String) params.get("remark");
        
        if (status == null) {
            return error("审批状态不能为空");
        }
        
        return toAjax(attendanceReapplyService.approveReapply(reapplyId, status, remark));
    }
    
    /**
     * 审批请假申请
     */
    @PreAuthorize("@ss.hasPermi('system:attendance:edit')")
    @Log(title = "请假申请审批", businessType = BusinessType.UPDATE)
    @PutMapping("/leave/approve/{leaveId}")
    public AjaxResult approveLeave(@PathVariable Long leaveId, @RequestBody Map<String, Object> params)
    {
        String status = (String) params.get("status");
        String remark = (String) params.get("remark");
        
        if (status == null) {
            return error("审批状态不能为空");
        }
        
        return toAjax(attendanceLeaveService.approveLeave(leaveId, status, remark));
    }
} 